package com.panda.web.service.general.impl;

import com.panda.web.domain.vo.commons.CityVO;
import com.panda.web.domain.vo.commons.ProvinceVO;
import com.panda.web.entity.py.Area;
import com.panda.web.mapper.py.AreaMapper;
import com.panda.web.service.general.GeneralService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Slf4j
@Service
public class GeneralServiceImpl implements GeneralService {

    @Autowired
    private AreaMapper areaMapper;

    /**
     * 返回特定格式的省市
     * @return
     */
    @Override
    public List<ProvinceVO> getAreaCity() {
        List<ProvinceVO> voList = new ArrayList<>();

        Area area = areaMapper.selectById(1);//中国
        List<Area>provonceList = areaMapper.findByValue(area.getValue());//所有省
        if (provonceList!=null&&!provonceList.isEmpty()){
            for (Area areaPro : provonceList) {
                ProvinceVO vo = new ProvinceVO();
                vo.setId(areaPro.getId());
                vo.setName(areaPro.getName());
                List<CityVO>cityVOList =new ArrayList<>();
                List<Area>cityList = areaMapper.findByValue(areaPro.getValue());//所有省
                if (cityList!=null&&!cityList.isEmpty()){
                    for (Area areaCity : cityList) {
                        CityVO cityVo = new CityVO();
                        cityVo.setId(areaCity.getId());
                        cityVo.setName(areaCity.getName());
                        cityVo.setState(false);
                        cityVOList.add(cityVo);
                    }
                }
                vo.setCityList(cityVOList);
                voList.add(vo);
            }
        }
        if (voList!=null&&!voList.isEmpty()){
            sortProvinces(voList);
        }
        return voList;
    }

    /**
     * 排序
     * @param voList
     */
    public void sortProvinces(List<ProvinceVO> voList) {

        // 对 voList 按照 id 排序
        voList.sort(Comparator.comparingLong(ProvinceVO::getId));

        // 为每个 ProvinceVO 设置 sort 值，sort 从 0 开始递增
        for (int i = 0; i < voList.size(); i++) {
            ProvinceVO province = voList.get(i);
            province.setSort(i); // 设置 sort 为递增值
        }
    }

}
